package de.mhus.lib.liferay.portlet;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import com.liferay.portal.kernel.util.ParamUtil;

import de.mhus.lib.core.MString;
import de.mhus.lib.core.logging.Log;
import de.mhus.lib.core.logging.MLogger;
import de.mhus.lib.portlet.actions.ActionRequestHandler;
import de.mhus.lib.portlet.resource.ResourceRequestHandler;

public abstract class LiferayMVCPortlet extends com.liferay.util.bridges.mvc.MVCPortlet {

	protected ResourceRequestHandler resourcesHandler = new ResourceRequestHandler();
	protected ActionRequestHandler actionsHandler = new ActionRequestHandler();
	protected Log log = MLogger.getLog(this.getClass());
	/**
	 * Set this to true if the view jsp needs parameters from the request.
	 */
	protected boolean viewNeedParameters = false;
	
	@Override
	public void init() throws PortletException {
		super.init();
		doInit();
	}		

	protected abstract void doInit() throws PortletException;
	
	
	
	@Override
	public void doView(RenderRequest renderRequest,
			RenderResponse renderResponse) throws IOException, PortletException {
		
		if (viewNeedParameters) {
			renderRequest = new RenderRequestWrapper(renderRequest);
		}
		if (!doFillViewAttributes(renderRequest, renderResponse)) return;
		super.doView(renderRequest, renderResponse);
	}

	/**
	 * Overwrite this method if you need to give attributes to the jsp page. Alternatively you can
	 * cancel or forward the request by manipulating the response. If you want to deny execution of
	 * the jsp page, return false. Otherwise return true.
	 * @param request 
	 * @param response
	 * @return true for normal operation, false if no jsp page should be executed
	 */
	protected boolean doFillViewAttributes(RenderRequest request, RenderResponse response) throws IOException, PortletException {
		return true;
	}

	@Override
	public void processAction(ActionRequest request, ActionResponse response)
			throws PortletException, IOException {
		
		String actionName = ParamUtil.getString(request, ActionRequest.ACTION_NAME);

		log.t("action",actionName);
		if (MString.isSet(actionName) && actionsHandler.processAction(actionName,request, response)) return;
		
		super.processAction(request, response);
	}
	
	@Override
	public void serveResource(ResourceRequest resourceRequest,
			ResourceResponse resourceResponse) throws IOException,
			PortletException {
				
		log.t("resource",resourceRequest.getResourceID());
		if (resourcesHandler.serveResource(new ResourceRequestWrapper(resourceRequest), resourceResponse)) return;
		
		super.serveResource(resourceRequest, resourceResponse);
	}

}
